import {defineStore} from 'pinia'

import {ref} from "vue";
import {generalOcr, healthReportOcr, medicalReportOcr} from "@/apis/BdOcr.js";
import {MedicalReportResult} from "@/pojo/ImageOcrResult/MedicalReportResult.js";
import {OcrResult} from "@/pojo/ImageOcrResult/GeneralOcrResult.js";
import {convertFileToUrl} from "@/utils/convertFileToUrl.js";
import {HealthReportResult} from "@/pojo/ImageOcrResult/HealthReportResult.js";


//创建一个返回结果的类
export const useOcrStore = defineStore('OcrStore',
    () => {

        //医疗识别报告，单次只能上传一张，所以可以在这里定义类，然后将数据导出，通用OCR可以上传多个，如果在全局定义一个，那么导出的是最后一个结果
        const medicalReportResult = new MedicalReportResult()
        //医疗诊断报告
        const healthReportResult=new HealthReportResult()


        //通用识别返回的答案集合
        const generalOcrResultList = ref([
            {
                url: '',
                alt: '',
                result: '',
                accuracy: ''
            }
        ]);


        //一张通用文字精确识别
        const getGeneralOcrText = async (file) => {

            const formData = new FormData()

            const res = await generalOcr(arrayBuffer);

            console.log("开始解析")

            const ocrResult = new OcrResult();
            ocrResult.parseJson(res);


        }


        //多张图片请求
        const getGeneralOcrTexts = async (fileList) => {
            generalOcrResultList.value = []; // 清空结果列表
            console.log("FileList", fileList)
            for (let index = 0; index < fileList.length; index++) {
                const file = fileList[index];

                const url = await convertFileToUrl(file.raw);

                //const url=URL.createObjectURL(file)
                const altText = `这是第${index + 1}张图片`;

                // Add the URL and alt text to the generalOcrResultList
                generalOcrResultList.value.push({
                    url: url,
                    alt: altText,
                    result: '',
                    accuracy: ''
                });

                let ocrResult = new OcrResult();
                //调用单词请求
                // const result = await getGeneralOcrText(file.raw);
                const formData = new FormData()
                console.log("file",file)
                console.log("file.raw",file.raw)
                formData.append('file', file.raw);
                console.log(formData)

                const res = await generalOcr(formData);
                ocrResult.parseJson(res)
                if (ocrResult.detailText != null) {
                    const lastResultIndex = generalOcrResultList.value.length - 1;
                    generalOcrResultList.value[lastResultIndex].result = ocrResult.detailText;
                    generalOcrResultList.value[lastResultIndex].accuracy = ocrResult.averageProbability;
                }
            }
        }


        //医疗报告单识别
        const getMedicalReportOcr = async (file) => {

            const formData = new FormData()
            formData.append('file', file);
            //请求识别
            const res = await medicalReportOcr(formData);
            //解析返回结果
            console.log("开始解析")

            try {
                medicalReportResult.parseJSON(res)
            } catch (error) {
                console.error(error)
            }

        }




        const getHealthReportOcr=async (file)=>{
            const formData = new FormData()
            formData.append('file', file);
            //请求识别
            const res = await healthReportOcr(formData);
            //解析返回结果
            console.log("开始解析")

            try {

                healthReportResult.parseJson(res)

            } catch (error) {
                console.error(error)
            }

        }

        /**
         * 转换函数
         * @param file
         * @returns {Promise<unknown>}
         */
        function fileToArrayBuffer(file) {
            return new Promise((resolve, reject) => {
                // 检查是否传入了有效的 File 对象
                if (!(file instanceof File)) {
                    reject(new Error("Invalid file object"));
                    return;
                }

                // 创建 FileReader 对象
                const reader = new FileReader();

                // 监听 FileReader 的 load 事件
                reader.onload = function(event) {
                    // event.target.result 包含了文件的 ArrayBuffer 数据
                    const arrayBuffer = event.target.result;
                    resolve(arrayBuffer); // 解析 Promise
                };

                // 监听 FileReader 的 error 事件
                reader.onerror = function(event) {
                    const error = event.target.error || new Error("Error reading file");
                    reject(error); // 拒绝 Promise
                };

                // 使用 FileReader 读取文件为 ArrayBuffer
                reader.readAsArrayBuffer(file);
            });
        }








        const clearMedicalReportText = async () => {
            //将保存的结果全部清空
            medicalReportResult.commonData = [];
            medicalReportResult.items = [];
            medicalReportResult.commonDataResultNum = 0;
            medicalReportResult.Item_row_num = 0;
            medicalReportResult.logId = null;
            medicalReportResult.resultList = {
                patientInfo: '',
                patientInfoHtml: '',
                checkItem: '',
                checkItemHtml: ''
            };

        }


        //解析医疗报告识别


        // 3. 以对象的格式把state和action return
        return {

            generalOcrResultList,
            medicalReportResult,
            healthReportResult,
            getGeneralOcrText,
            getGeneralOcrTexts,
            getMedicalReportOcr,
            getHealthReportOcr,
            clearMedicalReportText,

        }

    }, {            //持久化存储，存储到了浏览器中的localStorage
        persist: true
    }
)